<template>
  <div class="product-sales-container">
    <div class="header">
      <h2>商品销量统计</h2>
      <div class="filter-group">
        <el-radio-group v-model="timeType" @change="handleTimeTypeChange">
          <el-radio label="day">当日</el-radio>
          <el-radio label="month">当月</el-radio>
          <el-radio label="year">当年</el-radio>
          <el-radio label="custom">自定义</el-radio>
        </el-radio-group>

        <el-date-picker
            v-if="timeType === 'custom'"
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
        />
      </div>
    </div>

    <div class="stats-card-group">
      <el-card class="stat-card">
        <div class="stat-info">
          <p class="stat-label">总销量</p>
          <p class="stat-value">{{ totalQuantity }}</p>
          <p class="stat-desc">件商品</p>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-info">
          <p class="stat-label">热销商品</p>
          <p class="stat-value">{{ topProduct.name || '无' }}</p>
          <p class="stat-desc">销量: {{ topProduct.quantity }} 件</p>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-info">
          <p class="stat-label">滞销商品</p>
          <p class="stat-value">{{ bottomProduct.name || '无' }}</p>
          <p class="stat-desc">销量: {{ bottomProduct.quantity }} 件</p>
        </div>
      </el-card>
    </div>

    <div class="charts-row">
      <el-card class="chart-card">
        <div class="chart-container">
          <h3>商品销量排行</h3>
          <div ref="rankChartRef" class="chart"></div>
        </div>
      </el-card>

      <el-card class="chart-card">
        <div class="chart-container">
          <h3>商品类别占比</h3>
          <div ref="categoryChartRef" class="chart"></div>
        </div>
      </el-card>
    </div>

    <el-card class="chart-card">
      <div class="chart-container">
        <h3>销量趋势 (按类别)</h3>
        <div ref="trendChartRef" class="chart"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { ElRadioGroup, ElRadio, ElDatePicker, ElCard } from 'element-plus';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import http from '@/axios/http'
/* -------------------------------------------------
 * 1. 类型定义
 * ------------------------------------------------- */
interface Product {
  id: number;
  productName: string;
  productCategory: string;
  price: number;
}

interface Order {
  id: number;
  orderTime: string;
  remark: string;
}

/* -------------------------------------------------
 * 2. 响应式变量
 * ------------------------------------------------- */
const timeType = ref<'day' | 'month' | 'year' | 'custom'>('month');
const dateRange = ref<[string, string]>([]);
const filteredOrders = ref<Order[]>([]);
const totalQuantity = ref(0);
const topProduct = ref({ name: '', quantity: 0 });
const bottomProduct = ref({ name: '', quantity: 0 });
const selectedDate = ref('');          // 跨组件联动用

/* 图表 DOM 引用 */
const rankChartRef = ref<HTMLDivElement | null>(null);
const categoryChartRef = ref<HTMLDivElement | null>(null);
const trendChartRef = ref<HTMLDivElement | null>(null);
let rankChart: ECharts | null = null;
let categoryChart: ECharts | null = null;
let trendChart: ECharts | null = null;

/* 原始数据 */
let allProducts: Product[] = [];
let allOrders: Order[] = [];

/* -------------------------------------------------
 * 3. 工具：从备注里提取商品+数量
 * ------------------------------------------------- */
const extractProductsFromOrder = (remark: string) => {
  const list: { name: string; quantity: number }[] = [];
  remark.split(';').forEach(line => {
    const m = line.trim().match(/^(.+?)-(\d+)-/);
    if (m) list.push({ name: m[1].trim(), quantity: +m[2] });
  });
  return list;
};

/* -------------------------------------------------
 * 4. 获取后端数据
 * ------------------------------------------------- */
const fetchProducts = async () => {
  // 这里用你项目的真实前缀，/api 或者 http://localhost:8080 均可
  const { data } = await http.post('/glsb/get_all_products', { pageNum: 1, pageSize: 999 });
  allProducts = data.data?.list || [];
};

const fetchOrders = async () => {
  // 一次性拉全量订单（后端已支持）
  const { data } = await http.post('/glsb/get_all_orders', { pageNum: 1, pageSize: 9999 });
  const raw = data.data?.list || [];
  /* 13 位时间戳 -> yyyy-MM-dd */
  allOrders = raw.map((o: any) => ({
    ...o,
    orderTime: new Date(o.orderTime).toISOString().slice(0, 10)
  }));
};

/* -------------------------------------------------
 * 5. 过滤 / 统计 / 绘图
 * ------------------------------------------------- */
const filterOrders = () => {
  let list = [...allOrders];
  if (selectedDate.value) {
    list = list.filter(o => o.orderTime.startsWith(selectedDate.value));
  } else {
    const today = new Date();
    switch (timeType.value) {
      case 'day': {
        const d = today.toISOString().slice(0, 10);
        list = list.filter(o => o.orderTime.startsWith(d));
        break;
      }
      case 'month': {
        const m = today.toISOString().slice(0, 7);
        list = list.filter(o => o.orderTime.startsWith(m));
        break;
      }
      case 'year': {
        const y = today.getFullYear();
        list = list.filter(o => o.orderTime.startsWith(String(y)));
        break;
      }
      case 'custom': {
        if (dateRange.value.length === 2) {
          const [s, e] = dateRange.value;
          list = list.filter(o => o.orderTime >= s && o.orderTime <= e);
        }
        break;
      }
    }
  }
  filteredOrders.value = list;
};

const updateStats = () => {
  const qtyMap: Record<string, number> = {};
  filteredOrders.value.forEach(o => {
    extractProductsFromOrder(o.remark).forEach(p => {
      qtyMap[p.name] = (qtyMap[p.name] || 0) + p.quantity;
    });
  });
  totalQuantity.value = Object.values(qtyMap).reduce((a, b) => a + b, 0);
  const arr = Object.entries(qtyMap)
      .map(([name, quantity]) => ({ name, quantity }))
      .sort((a, b) => b.quantity - a.quantity);
  topProduct.value = arr[0] || { name: '', quantity: 0 };
  bottomProduct.value = arr[arr.length - 1] || { name: '', quantity: 0 };
};

/* -------------------------------------------------
 * 6. 图表渲染（仅换数据源，逻辑不变）
 * ------------------------------------------------- */
const renderRankChart = () => {
  if (!rankChartRef.value) return;
  rankChart && rankChart.dispose();
  rankChart = echarts.init(rankChartRef.value);

  const qtyMap: Record<string, number> = {};
  filteredOrders.value.forEach(o => {
    extractProductsFromOrder(o.remark).forEach(p => {
      qtyMap[p.name] = (qtyMap[p.name] || 0) + p.quantity;
    });
  });
  const arr = Object.entries(qtyMap)
      .map(([name, quantity]) => ({ name, quantity }))
      .sort((a, b) => b.quantity - a.quantity)
      .slice(0, 10);

  rankChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'value', axisLabel: { formatter: '{value} 件' } },
    yAxis: { type: 'category', data: arr.map(i => i.name), inverse: true },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: arr.map(i => i.quantity),
        itemStyle: { color: '#67c23a' }
      }
    ]
  });
};

const renderCategoryChart = () => {
  if (!categoryChartRef.value) return;
  categoryChart && categoryChart.dispose();
  categoryChart = echarts.init(categoryChartRef.value);

  const map: Record<string, number> = {};
  filteredOrders.value.forEach(o => {
    extractProductsFromOrder(o.remark).forEach(p => {
      const prd = allProducts.find(k => k.productName === p.name);
      const cat = prd?.productCategory || '其他';
      map[cat] = (map[cat] || 0) + p.quantity;
    });
  });

  const data = Object.entries(map).map(([name, value]) => ({ name, value }));
  categoryChart.setOption({
    tooltip: { trigger: 'item' },
    legend: { orient: 'horizontal', bottom: 0 },
    series: [
      {
        name: '商品类别',
        type: 'pie',
        radius: ['40%', '70%'],
        data
      }
    ]
  });
};

const renderTrendChart = () => {
  if (!trendChartRef.value) return;
  trendChart && trendChart.dispose();
  trendChart = echarts.init(trendChartRef.value);

  const dateCat: Record<string, Record<string, number>> = {};
  const cats = new Set<string>();
  filteredOrders.value.forEach(o => {
    const d = o.orderTime;
    extractProductsFromOrder(o.remark).forEach(p => {
      const prd = allProducts.find(k => k.productName === p.name);
      const cat = prd?.productCategory || '其他';
      cats.add(cat);
      if (!dateCat[d]) dateCat[d] = {};
      dateCat[d][cat] = (dateCat[d][cat] || 0) + p.quantity;
    });
  });
  const dates = Object.keys(dateCat).sort();
  const category = Array.from(cats);
  const series = category.map(cat => ({
    name: cat,
    type: 'line',
    smooth: true,
    data: dates.map(d => dateCat[d][cat] || 0)
  }));

  trendChart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: category },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: dates },
    yAxis: { type: 'value', axisLabel: { formatter: '{value} 件' } },
    series
  });
};

const renderCharts = () => {
  renderRankChart();
  renderCategoryChart();
  renderTrendChart();
};

/* -------------------------------------------------
 * 7. 事件
 * ------------------------------------------------- */
const handleTimeTypeChange = () => {
  filterOrders();
  updateStats();
  renderCharts();
};
const handleDateRangeChange = () => {
  filterOrders();
  updateStats();
  renderCharts();
};

/* -------------------------------------------------
 * 8. 生命周期
 * ------------------------------------------------- */
onMounted(async () => {
  await fetchProducts();
  await fetchOrders();
  filterOrders();
  updateStats();
  renderCharts();

  /* 监听销售额页面联动 */
  window.addEventListener('sales-date-selected', (e: any) => {
    selectedDate.value = e.detail.date;
    filterOrders();
    updateStats();
    renderCharts();
  });

  window.addEventListener('resize', () => {
    rankChart?.resize();
    categoryChart?.resize();
    trendChart?.resize();
  });
});

watch(filteredOrders, renderCharts);
</script>

<style scoped>
.product-sales-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  gap: 15px;
  align-items: center;
}

.stats-card-group {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
}

.stat-info {
  text-align: center;
  padding: 15px 0;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-desc {
  color: #606266;
  font-size: 14px;
}

.charts-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.chart-card {
  flex: 1;
  min-width: 400px;
  margin-bottom: 20px;
}

.chart-container {
  padding: 15px;
}

.chart {
  width: 100%;
  height: 400px;
  margin-top: 15px;
}
</style>